package com.example.security;

import cn.hutool.json.JSONUtil;
import com.example.common.lang.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录失败处理器
 */

@Component                  //作用：用于把当前类对象存入spring容器中
public class LoginFailureHandler implements AuthenticationFailureHandler {  //继承security的登录失败处理器

    //security的登录失败处理器重写
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {

        response.setContentType("application/json;charset=UTF-8");  //返回数据为json格式，utf-8编码
        ServletOutputStream outputStream = response.getOutputStream();  //生成输出流准备用输出流的方式flush推出

        Result result = Result.fail(exception.getMessage());    //用统一结果数据封装类，并返回失败异常消息

        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));   //把Result序列化成json的字节码utf-8格式

        outputStream.flush();       //把流推出
        outputStream.close();       //释放资源

    }
}
